#!/bin/bash

###################################################
# zhangjd01<zhangjd01@zts.com.cn>
# 2022.11.8
# -t 指定git checkout参数，不指定默认使用最新的tag
#	 可以指定tag或者master分支
###################################################

# 获取输入参数
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
    -t)
    TAG="$2"
    shift
    ;;
    *)
      # unknown option
      echo "Unknown argument: $1"
    ;;
esac
shift
done

# 执行git clone
function git_clone (){
/usr/bin/expect << EOF
    spawn git clone https://git.qilu-dev.com/develop2/rpa-irobot.git

    expect {
	"Username" {send "zhangjd01\r"}
    }
    expect {
	"Password" {send "080451zjD080451zjD\r"}
    }

    expect eof
EOF
}

if [ ! -d "rpa-irobot" ]
then
    echo "-----------------------------------git clone start--------------------------------------------"
    git_clone  
    #sleep 2
    echo "-----------------------------------git clone finish-------------------------------------------"
fi

# 执行git pull
function git_pull (){
/usr/bin/expect << EOF
    spawn git pull origin master

    expect {
	"Username" {send "zhangjd01\r"}
    }
    expect {
	"Password" {send "080451zjD080451zjD\r"}
    }

    expect eof
EOF
}

cd rpa-irobot
echo "-----------------------------------git pull start------------------------------------------"
git_pull  
echo "-----------------------------------git pull finish-----------------------------------------"

# checkout到最近的tag或者master
if [ ! $TAG ]
then
    TAG=$(git describe --tags $(git rev-list --tags --max-count=1))
fi

echo "-----------------------------------git checkout $TAG start--------------------------------"
git checkout $TAG 
echo "-----------------------------------git checkout $TAG finish--------------------------------"

# 构建并push镜像
echo "-----------------------------------build&push image start--------------------------------"
docker rmi harbor.zts.com.cn/snapshot/rpa-irobot:latest 
docker build -t harbor.zts.com.cn/snapshot/rpa-irobot:latest . 
#docker push harbor.zts.com.cn/snapshot/rpa-irobot:latest
echo "-----------------------------------build&push image finish--------------------------------"

echo "-----------------------------------git log------------------------------------------------"
git log -5 --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
echo "-----------------------------------git log------------------------------------------------"

# 升级
read -p "确定使用 $TAG 升级？（请输入y/n）：" INPUT

if [ $INPUT == "y"  ]
then
    echo "-----------------------------------upgrade start-------------------------------------------"
    kubectl delete -f /opt/zts/k8s/zts_api/zts-cloud-platform-rpa-irobot-deployment.yaml
    kubectl create -f /opt/zts/k8s/zts_api/zts-cloud-platform-rpa-irobot-deployment.yaml
    echo "-----------------------------------upgrade finish------------------------------------------"
    echo 'kubectl get po|grep rpa-irobot'
fi

